/**
 * 获取当前页面路径
 * @param boolean isGetParam  是否返回带有url参数的路径
 */
export function getCurrentPageUrl(isGetParam) {
  var pages = getCurrentPages();
  var currentPage = pages[pages.length - 1];
  var url = currentPage.route;
  var options = currentPage.options;
  if (isGetParam) {
    let urlWithArgs = `/${url}?`;
    for (let key in options) {
      urlWithArgs += `${key}=${options[key]}&`
    }
    return urlWithArgs.substring(0, urlWithArgs.length - 1);
  }
  return "/" + url;
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (`${d.getMonth()+1}月${d.getDate()}日${d.getHours()}时${d.getMinutes()}分`)
  }
}

/**
 * 函数防抖
 *@param {function} func 执行函数
 *@param {number} delay 延时执行毫秒数
 *@param {boolean} type true-第一次，false-最后一次
 */
export function debounce(func, delay, type = true) {
  let timer = null;
  return function () {
    if (timer) clearTimeout(timer);
    if (type) {
      let isFirst = !timer;
      timer = setTimeout(() => timer = null, delay);
      if (isFirst) func.apply(this, arguments);
    } else {
      timer = setTimeout(func.apply(this, arguments), delay);
    }
  }();
}

/**
 * 取出 url 上的参数变为对象
 * @param {string} url
 * @returns {Object}
 */
export function urlParam2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 参数变为数组
 * @param {string} param 
 */
export function param2Obj(param) {
  const obj = {}
  const searchArr = param.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 对象变为参数拼接起来
 * @param {Object} obj
 */
export function obj2Param(obj) {
  var paramArray = [];
  for (let key in obj) {
    paramArray.push(key + "=" + obj[key]);
  }
  let j = paramArray.join("&");
  return j;
}

/**
 * 格式化价格 - 保留一位小数
 * 12.0 -> 12
 * 12.9 -> 12
 * @param {number} price 
 */
export function formatPrice(price) {
  const arr = price.toFixed(1).split('.');
  if (arr[1] === '0') {
    return arr[0];
  } else {
    return arr.join('.');
  }
}

/**
 * 打开文件
 * @param {string} url: 文件链接
 * @param {string} type: 文件类型，默认 doc
 */
export function openFile(url, type = 'doc') {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '正在打开文件...',
      mask: true
    });
    wx.downloadFile({
      url: url,
      success: res => {
        wx.hideLoading();
        const path = res.tempFilePath;
        wx.openDocument({
          filePath: path,
          fileType: type,
          success: res => {
            resolve(res);
          },
          fail: err => {
            reject(err);
          }
        })
      },
      fail: err => {
        wx.hideLoading();
        reject(err);
      }
    })
  })
}

/**
 * 获取订阅消息授权
 * @param {array} tmplIds 订阅消息模板的id集合
 */
export function getSubscribeMessageAuth(tmplIds) {
  return new Promise(resolve => {
    wx.requestSubscribeMessage({
      tmplIds: tmplIds,
      success(res) {
        // console.log(res)
        resolve()
      },
      fail(err) {
        // console.log(err)
        if (err.errCode === '20004') {
          wx.showToast({
            title: '请打开订阅消息以便接收通知',
            icon: 'none'
          })
          wx.openSetting({
            withSubscriptions: true,
          })
        }
        wx.showToast({
          title: `发生错误：${err.errCode}`,
          icon: 'none'
        })
      }
    })
  })

}

/**
 * 把分钟转换成有小时有秒
 * @param {Number} time 分钟
 */
export function formatParkingTime(time) {
  if (time <= 60) {
    return `${time}分`
  } else if (time > 60) {
    const mH = ~~(time/60)
    const mM = ~~(time%60)
    return `${mH}小时${mM}分`
  }
}


